package com.jinyang.jetpackdemo.paging3

import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/8/16
 * @Description:2. 配置数据源：自定义一个子类去继承 PagingSource，然后重写 load() 函数，并在这里提供对应当前页数的数据
 */
class RepoPagingSource(private val apiService: ApiService) : PagingSource<Int, Repo>() {
    override fun getRefreshKey(state: PagingState<Int, Repo>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
            val repoResponse = apiService.searRepos(page, pageSize)
            val repoItems = repoResponse.items
            val prevKey = if (page > 1) page - 1 else null
            val nextKey = if (repoItems.isNotEmpty()) page + 1 else null
            LoadResult.Page(repoItems, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}